package dataStructure.tree;

/**
 * @author lhn
 * @date 2024-09-03 16:48
 */

public class ArrBinaryTreeDemo {
    public static void main(String[] args) {
        int arr[] = {1, 2, 3, 4, 5, 6, 7};
        ArrBinaryTree_ arrBinaryTree_ = new ArrBinaryTree_(arr);
//        arrBinaryTree_.preOrder();
        arrBinaryTree_.postOrder();
    }
}

class ArrBinaryTree_ {
    private int arr[]; //存储数据节点的数组

    public ArrBinaryTree_(int[] arr) {
        this.arr = arr;
    }

    //重载
    public void preOrder() {
        this.preOrder(0);
    }

    //前序遍历
    public void preOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("数组为空，不能按照二叉树的前序遍历");
            return;
        }
        System.out.println(arr[index]);
        //向左递归遍历，遍历左子树
        if ((index * 2 + 1) < arr.length) preOrder(2 * index + 1);
        //向右递归遍历，遍历右子树
        if ((index * 2 + 2) < arr.length) preOrder(2 * index + 2);
    }

    public void postOrder() {
        this.postOrder(0);
    }

    //前序遍历
    public void postOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("数组为空，不能按照二叉树的前序遍历");
            return;
        }
        if ((index * 2 + 1) < arr.length) preOrder(2 * index + 1);
        if ((index * 2 + 2) < arr.length) preOrder(2 * index + 2);
        System.out.println(arr[index]);

    }
}